/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
/*
 * main.cc
 * Copyright (C) 2012 - 2014 Massimiliano Maniscalco <max.maniscalco@gmail.com>
 * 
 * LiberAcus is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * LiberAcus is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <gtkmm.h>
#include <iostream>
#include "controller.h"
#include "config.h"


#ifdef ENABLE_NLS
#include <libintl.h>
#endif


/* utent interface file for installed program */
#define UI_FILE PACKAGE_DATA_DIR"/ui/liberacus.ui"

/* utent interface file for developing and testing */
//#define UI_FILE "src/liberacus.ui"

using namespace std;

Gtk::Window* main_win;
Controller* main_ctrl;

// check if data need to be saved
bool
on_quitting(void)
{
	if (main_ctrl->should_save())
	{
		int res_id = Gtk::RESPONSE_YES;
		if (main_ctrl->chiedi_prima_salvare())
		{
			Gtk::MessageDialog *_alertDialog = new Gtk::MessageDialog(*main_win, "Vuoi salvare i dati modificati prima di uscire?", false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_YES_NO, true);
			res_id = _alertDialog->run();
			delete _alertDialog;
		}
		if (res_id == Gtk::RESPONSE_YES)
		{
			if (main_ctrl->should_save_clienti())
				main_ctrl->save_data(main_ctrl->get_clienti_file_path(), SAVE_CLIENTI);
			if (main_ctrl->should_save_prestazioni())
				main_ctrl->save_data(main_ctrl->get_prestazioni_file_path(), SAVE_PRESTAZIONI);
			if (main_ctrl->should_save_ricevute())
				main_ctrl->save_data(main_ctrl->get_ricevute_file_path(), SAVE_RICEVUTE);
		}
	}
	return true;
}

int
main(int argc, char* argv[])
{
	Glib::RefPtr<Gtk::Application> kit;
	kit = Gtk::Application::create(argc, argv, "org.maniscalco.liberacus", Gio::APPLICATION_FLAGS_NONE);


	//Load the Glade file and instiate its widgets:
	Glib::RefPtr<Gtk::Builder> builder;
	try
	{
		builder = Gtk::Builder::create_from_file(UI_FILE);
	}
	catch (const Glib::FileError & ex)
	{
		std::cerr << ex.what() << std::endl;
		return 1;
	}

	main_ctrl = new Controller(builder, kit);
	main_win = main_ctrl->get_main_window();

	if (main_win)
	{
		kit->run(*main_win);
		on_quitting();
	}
	
	delete main_ctrl;
	
	return 0;
}
